package models

import (
	"errors"
	"fmt"
	"github.com/astaxie/beego/orm"
)

var (
	UserList map[string]*User
)

func init() {

}

type User struct {
	Id       int  		`orm:"pk;auto"`
	Username string  	`json:"name"`
	Password string		`json:"password"`
	phone    string
	Profile  *Profile	`orm:"rel(one);null"`
}

type Profile struct {
	Id 		int			`orm:"pk;auto"`
	Gender  string
	Age     int
	Address string
}

func init() {
	orm.RegisterModel(new(User), new(Profile))
}

func AddUser(u User) int {
	o := orm.NewOrm()
	if u.Profile == nil {
		profile := Profile{Address: "北京", Age: 10}
		_, err := o.Insert(&profile)
		if err != nil {
			fmt.Printf("%s\n", err)
		}
		u.Profile = &profile
	}
	_, err := o.Insert(&u)
	if err != nil {
		fmt.Printf("%s\n", err)
	}
	return u.Id
}

func GetUser(uid string) (u *User, err error) {
	if u, ok := UserList[uid]; ok {
		return u, nil
	}
	return nil, errors.New("User not exists")
}

func GetAllUsers() map[string]*User {
	return UserList
}

func UpdateUser(uid string, uu *User) (a *User, err error) {

	return nil, errors.New("User Not Exist")
}

func Login(username, password string) bool {
	for _, u := range UserList {
		if u.Username == username && u.Password == password {
			return true
		}
	}
	return false
}

func DeleteUser(uid string) {
	delete(UserList, uid)
}
